package wypozyczalnia.config;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

public class ApplicationProperties extends Properties {

	private static final long serialVersionUID = -2901409683834928677L;

	private final static String PROPERTIES_RESOURCE = "/default.properties";

    private final Logger logger = Logger.getLogger(this.getClass());

    public ApplicationProperties(String envKeyToProperties) {
        loadDefaultProps();
        loadFromClasspath("/" + envKeyToProperties + ".properties");
        setSystemProperties();
    }

    private void setSystemProperties() {
        setSystemProperty("mom.discreteevents.disable", "false");
        setSystemProperty("mom.metrics.disable", "false");
        setSystemProperty("oracle.net.CONNECT_TIMEOUT", "10000");    
        setSystemProperty("oracle.jdbc.ReadTimeout", "10000");
    }

    private final void setSystemProperty(String name, String dflt) {
        System.setProperty(name, this.getProperty(name, dflt));
    }

    private void loadDefaultProps() {
        logger.info("Reading default properties from classpath: " + PROPERTIES_RESOURCE);
        InputStream is = null;
        try {
            is = getClass().getResourceAsStream(PROPERTIES_RESOURCE);
            if (is == null)
                throw new FileNotFoundException(PROPERTIES_RESOURCE);
            load(is);
        } catch (Exception ex) {
            logger.fatal("CANNOT READ default.properties", ex);
            throw new RuntimeException(ex);
        } finally {
            //IOUtils.closeQuietly(is);
        }
    }

    private void loadFromClasspath(String path) {
        logger.info("Trying to read properties from: " + path);
        InputStream is = null;
        try {
            is = getClass().getResourceAsStream(path);
            if (is == null) {
                logger.warn("WARN: properties not found on classpath: " + path);
                return;
            }
            logger.info("Loading properties from: " + path);
            load(is);
        } catch (Exception ex) {
            logger.fatal("CANNOT READ " + path, ex);
            throw new RuntimeException(ex);
        } finally {
            //IOUtils.closeQuietly(is);
        }
    }

    public String getEnvironmentId() {
    	return super.getProperty("environment");
    }
}
